package com.xiaomo.core;

import java.util.List;

import com.xiaomo.model.MultiUnit;
import com.xiaomo.model.Schedule;
import com.xiaomo.model.SingleUnit;
import com.xiaomo.model.Task;
import com.xiaomo.model.Unit;
import com.xiaomo.utils.LogUtil;

public class TaskExecute {
	
	private static final LogUtil log = new LogUtil(TaskExecute.class);
	
	public  static void start(Task task ){
		List<Schedule> listSchedules = task.getSchedules();
		Schedule schedule = null;
			for (int i = 0; i < listSchedules.size(); i++) {
				schedule = listSchedules.get(i);
				runUnit(schedule.getThisUnit());
			}
	}
	
	private static void runUnit(Unit unit){
		if (unit.getType().equals(TaskEnum.single.toString())) {
			runSingleUnit(unit);
		}else if (unit.getType().equals(TaskEnum.multi.toString()))  {
			runMultiUnit(unit);
		}
	}

	private static void runMultiUnit(Unit unit) {
		MultiUnit thisMultiUnit =  (MultiUnit) unit;
		List<SingleUnit> listSingleUnits =   thisMultiUnit.getSubunits();
		ThreadGroup threadGroup = new ThreadGroup(thisMultiUnit.getName());
		for (int j = 0; j < listSingleUnits.size(); j++) {
			new Thread(threadGroup,listSingleUnits.get(j).getExecuteClass(),listSingleUnits.get(j).getExecuteClassName()).start();
			log.info(String.format("%s 正在执行", listSingleUnits.get(j).getExecuteClassName()));
		}
		try {
			while (threadGroup.activeCount() != 0 ) {
				Thread.sleep(100L);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	private static void runSingleUnit(Unit unit) {
		SingleUnit thisSingleUnit = (SingleUnit) unit;
		//单线程的时候直接这样调用运行就行
		thisSingleUnit.getExecuteClass().execute();
		log.info(String.format("%s 正在执行", thisSingleUnit.getExecuteClassName()));
	}


}
